import React from "react";
import { FlatList, Image, StyleSheet, Text } from "react-native";
import { View,TouchableOpacity } from "react-native-ui-lib";
import { commonStyles } from "../../configs/commonStyle";
import navigator from "../../utils/navigator";
import BasePage from "../BasePage";
import ListEmpty from "../common/ListEmpty";
import ListFooter from "../common/ListFooter";
import { IconImage } from "../../utils";
import ReplyDialog from "../common/ReplyDialog";
import NavigationBar from "../common/NavigationBar";
import ViewUtils from "../../utils/ViewUtils";
import DateFilter from "../components/DateFilter";
import AudioRecorderPlayer from "react-native-audio-recorder-player";
import moment from "moment";
import { inject, observer } from "mobx-react";

/**
 * 订单地图列表模式
 */
@inject("userStore", "appStore")
@observer
export default class MapOrderList extends BasePage {

  constructor(props) {
    super(props);
    const {delyStartTime,delyEndTimeEnd,dateType}=this.props.navigation.state.params;
    logger('时间1',this.props.navigation.state.params)
    this.pageNo = 1;
    this.pageSize = 15;
    this.totalPages = 0;
    this.isLoading = false;
    this.isFirst = true;
    this.timeLong = 0;
    this.audioRecorderPlayer = new AudioRecorderPlayer();
    this.state = {
      isRefreshing: false,
      showFoot: 0,
      showEmpty: false,
      dataList: [],
      delyStartTime: delyStartTime?delyStartTime:moment().format("YYYY-MM-DD"),
      delyEndTimeEnd: delyEndTimeEnd?delyEndTimeEnd:moment().format("YYYY-MM-DD"),
      recordSecs: 0,
      recordTime: "",
      dateType:dateType||0,
    };
  }

  componentDidMount() {
    super.componentDidMount();
    this.loadData(false);
    // this.props.userStore.setValue('hasNewOrder', false);
    // this.refreshOrderList = Events.subscribe('RefreshOrderList', () => this._renderRefresh(false));
  }


  loadData(showLoading = false) {
    const { dataList, delyStartTime, delyEndTimeEnd } = this.state;
    const { userInfo } = this.props.userStore;
    this.isLoading = true;
    let params = {
      pageNum: this.pageNo,
      pageSize: this.pageSize,
      token: global.token,
      // token: '6551245572408320',
      distributorId: userInfo.distributorId,
      ordState: 6,
      delyStartTime: `${delyStartTime} 00:00:00`,
      delyEndTimeEnd: `${delyEndTimeEnd} 23:59:59`,
      showLoading,
    };
    axios.get(api.queryOrder, { params })
      .then(res => {
        this.isLoading = false;
        logger("查询结果", res.pages);
        let tempArr = [];
        let showf;
        this.totalPages = res.pages;
        if (this.pageNo == 1) {
          tempArr = res.list || [];
          showf = 0;
        } else {
          tempArr = dataList.concat(res.list);
          showf = (this.pageNo == this.totalPages) ? 1 : 0;
        }
        this.setState({
          //复制数据源
          dataList: tempArr,
          showFoot: showf,
          isRefreshing: false,
          showEmpty: (this.pageNo == 1 && tempArr.length == 0 ? true : false),
        });
      })
      .catch(e => {
        logger("error", e);
        this.isLoading = false;
        this.setState({
          isRefreshing: false,
          showEmpty: (this.pageNo == 1 ? true : false),
        });
      });
  }

  _onEndReached = async () => {
    //如果是正在加载中或到底了，则返回
    if (this.state.showFoot != 0) {
      return;
    }
    //如果当前页大于或等于总页数，那就是到最后一页了，返回
    if (this.pageNo == this.totalPages || this.totalPages == 0) {
      return;
    } else {
      this.pageNo++;
    }
    //底部显示正在加载更多数据
    this.setState({ showFoot: 2 });
    //获取数据
    this.loadData(false);
  };

  // 下拉刷新
  _renderRefresh = (isRefreshing = true) => {
    // 不处于 下拉刷新
    if (this.isLoading === false && !this.state.isRefreshing) {
      this.setState({
        isRefreshing,
      });
      this.pageNo = 1;
      this.totalPages = 0;
      this.loadData();
    }
  };

  render_item = ({ item, index }) => {
    const { delyStartTime,delyEndTimeEnd,dateType} = this.state;
    return (
      <TouchableOpacity activeOpacity={1} onPress={()=>navigator.navigate("OrderDetails",{ordNo:item.ordNo})}>
        <View style={styles.titleWrap}>
          <Text style={commonStyles.text_black_14}>单号：{item?.xmbzNo}({item?.delySTime}-{item?.delyETime})</Text>
          <TouchableOpacity activeOpacity={1} onPress={()=>navigator.navigate('MapOrder',{
            delyStartTime,delyEndTimeEnd,dateType,centerLocation:{
              latitude: item?.addressLng||22.616282489952997,
              longitude: item?.addressLat||114.1345043622764,
            }})}>
          <Image source={IconImage.ic_location} style={{width:25,height:25}} />
          </TouchableOpacity>
        </View>
        <View style={styles.contentWrap}>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_gray_13}>分仓</Text>
            <Text style={commonStyles.text_black_13}>{item?.invoiceHeader}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_gray_13}>联系电话</Text>
            <Text style={commonStyles.text_black_13}>{item?.cneeTel}</Text>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_gray_13}>地址</Text>
            <View marginL-10 flex right>
              <Text style={commonStyles.text_black_13}>{item?.address1}</Text>
            </View>
          </View>
          <View style={styles.itemWrap}>
            <Text style={commonStyles.text_gray_13}>商品</Text>
            <View marginL-10 flex right>
              {
                item.orderDetailList && item.orderDetailList.map(data => {

                  return (
                    <View row marginT-5>
                        <Text
                          style={commonStyles.text_black_13}>{data?.goodsName}（{data?.goodsSpecs}）(x{data?.num}）</Text>
                    </View>
                  );
                })
              }
            </View>
          </View>
        </View>
      </TouchableOpacity>
    );
  };

  render() {
    const { dataList, isRefreshing ,delyStartTime,delyEndTimeEnd,dateType} = this.state;

    logger('时间',delyStartTime,delyEndTimeEnd,dateType)
    return (
      <View useSafeArea style={commonStyles.body_primary}>
        <NavigationBar
          title={"订单地图"}
          backgroundColor={'transparent'}
          leftButton={ViewUtils.getLeftButton(() => this._onBackPress())}
          rightButton={ViewUtils.getRightTextBtn('切换地图',() => navigator.navigate('MapOrder',{delyStartTime,delyEndTimeEnd,dateType}))}
        />
        <View style={commonStyles.container}>
          <DateFilter begin={delyStartTime} to={delyEndTimeEnd} type={dateType} onQueryClick={(delyStartTime, delyEndTimeEnd,dateType) => this.setState({
            delyStartTime,
            delyEndTimeEnd,
            dateType
          }, () => this._renderRefresh(false))} />

          <FlatList
            data={dataList}
            onRefresh={this._renderRefresh}
            showsVerticalScrollIndicator={false}
            refreshing={isRefreshing}
            extraData={this.state}
            style={{}}
            contentContainerStyle={{ flexGrow: 1 }}
            keyExtractor={(item, index) => "menu_" + index}
            renderItem={this.render_item}
            ListEmptyComponent={() => <ListEmpty showEmpty={this.state.showEmpty} />}
            onEndReached={this._onEndReached}
            onEndReachedThreshold={0.1}
            ListFooterComponent={() => <ListFooter showFoot={this.state.showFoot} page={this.pageNo} />}
          />
          <ReplyDialog ref={r => this.replyDialog = r} callBack={(content) => this.addDiscuss(content)} />
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  titleWrap: {
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
    borderTopLeftRadius: 4,
    borderTopRightRadius: 4,
    backgroundColor: "#F9D63B",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
    marginTop: 15,
  },

  contentWrap: {
    backgroundColor: "white",
    marginHorizontal: 15,
    paddingHorizontal: 15,
    paddingVertical: 10,
  },

  itemWrap: {
    justifyContent: "space-between",
    flexDirection: "row",
    alignItems: "center",
    paddingVertical: 6,
  }

});
